package org.crystalrange.files.web;

import java.util.List;

import org.crystalrange.files.model.File;
import org.crystalrange.files.service.FileService;
import org.zkoss.zk.ui.Component;
import org.zkoss.zk.ui.event.Event;
import org.zkoss.zk.ui.util.GenericForwardComposer;
import org.zkoss.zkplus.databind.AnnotateDataBinder;
import org.zkoss.zul.Messagebox;
import org.zkoss.zul.Window;

import com.googlecode.genericdao.search.Search;

public class FileSelectController extends GenericForwardComposer {

	protected FileService fileService;
	protected File selectedFile;
	protected List<File> files;
	protected Search searchFile;
	protected AnnotateDataBinder binder;

	public FileService getFileService() {
		return fileService;
	}

	public void setFileService(FileService fileService) {
		this.fileService = fileService;
	}

	public File getSelectedFile() {
		return selectedFile;
	}

	public void setSelectedFile(File selectedFile) {
		this.selectedFile = selectedFile;
	}

	public List<File> getFiles() {
		return files;
	}

	public void setFiles(List<File> files) {
		this.files = files;
	}

	@Override
	public void doAfterCompose(Component component) throws Exception {
		super.doAfterCompose(component);
		this.searchFile = new Search(File.class);
		this.searchFile.setMaxResults(100);
		this.searchFile.addFetch("createdBy");
		this.files = this.fileService.search(this.searchFile);
		component.setAttribute("controller", this);
	}

	public void onClick$buttonOk(Event event) throws Exception {
		if (this.selectedFile != null) {
			this.execution.setAttribute("selectedFile", this.selectedFile);
			this.execution.setAttribute("result", "ok");
			this.self.detach();
		} else {
			Messagebox.show("Please select a File.");
		}
	}

	public void onClick$buttonCancel(Event event) throws Exception {
		this.execution.setAttribute("selectedFile", null);
		this.execution.setAttribute("result", "cancel");
		this.self.detach();
	}

	public void onClick$buttonSearch(Event event) throws Exception {
		this.execution.setAttribute("searchFile", this.searchFile);

		Window window = (Window) this.execution.createComponents(
				"~./zul/html/fileSearch.zul", null, null);
		window.setParent(self);
		window.doModal();

		if (this.execution.getAttribute("result") == "ok") {
			this.searchFile = (Search) this.execution
					.getAttribute("searchFile");
		}

		this.files = this.fileService.search(this.searchFile);
		this.binder.loadAll();
	}

}
